package com.xdxc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xdxc.model.entity.Subject;
import com.xdxc.response.Result;
import com.xdxc.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/subject")
public class SubjectController {

    @Autowired
    private SubjectService subjectService;

    // 分页查询科目列表
    @GetMapping("/page")
    public Result<Page<Subject>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {

        Page<Subject> page = new Page<>(current, size);
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();

        if (name != null && !name.isEmpty()) {
            wrapper.like("name", name);
        }

        wrapper.orderByAsc("sort");
        return Result.success(subjectService.page(page, wrapper));
    }

    // 获取所有科目列表（树形结构）
    @GetMapping("/tree")
    public Result<List<Subject>> getSubjectTree() {
        return Result.success(subjectService.getSubjectTree());
    }

    // 获取所有科目列表（扁平结构）
    @GetMapping("/list")
    public Result<List<Subject>> getAllSubjects() {
        return Result.success(subjectService.list());
    }

    // 根据ID获取科目详情
    @GetMapping("/{id}")
    public Result<Subject> getById(@PathVariable Long id) {
        return Result.success(subjectService.getById(id));
    }

    // 新增科目
    @PostMapping
    public Result<Boolean> add(@RequestBody Subject subject) {
        return Result.success(subjectService.save(subject));
    }

    // 修改科目
    @PutMapping
    public Result<Boolean> update(@RequestBody Subject subject) {
        return Result.success(subjectService.updateById(subject));
    }

    // 删除科目
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(subjectService.removeById(id));
    }
}